import { defineStore } from "pinia"
import { ElMessage } from "element-plus";
export const cnyzsUserpinia = defineStore("cnyzsUserpinia", {
   state: () => ({
      userinfo: {} as any,
      money: 0,
      token: useCookie("CNYZSTOKEN", { sameSite: "strict" }) || '',

      // 未读消息数
      notificationNumber: 0,
      commentReply: [] as any,
      commentStstusTotal: 0,
   }),
   getters: {
      // 未读消息数
      unreadTotal(state) {
         return state.notificationNumber
      }
   },
   actions: {

      // 获取用户信息
      async getUserinfo() {
         if (!this.token) return
         const res: any = await cnyzsRequest('/api/user/info', { method: 'GET' })
         if (res.status !== 200) {
            if (process.client) {
               // 删除TOKEN 清楚COOKIE
               this.userinfo = {}
               this.token = ''
               const cookie = useCookie("CNYZSTOKEN", { sameSite: "strict" })
               cookie.value = undefined
               cnyzsCommonpinia().openLogin = true
               return ElMessage.error(res.message)
            }
         } else {
            if (res.data) {
               this.userinfo = res.data
               this.money = res.data.money
            } else {
               if (process.client) {
                  // 删除TOKEN 清楚COOKIE
                  this.userinfo = {}
                  this.token = ''
                  const cookie = useCookie("CNYZSTOKEN", { sameSite: "strict" })
                  cookie.value = undefined
                  cnyzsCommonpinia().openLogin = true
                  return ElMessage.error('TOKEN失效，请重新登录')
               }
            }
         }
      },

      // 退出登录
      async outlogin() {
         this.userinfo = {}
         this.token = ''
         const cookie = useCookie("CNYZSTOKEN", { sameSite: "strict" })
         cookie.value = undefined
         ElMessage.success('退出成功')
         // window.open('/', "_self")
      },

      // 获取用户消息通知数量【只获取当前用户未读消息数量】
      async getUserNotificationNumber() {
         if (!this.token) return
         const res: any = await cnyzsRequest('/api/notification/get-user-notification-number', { method: 'POST' })
         if (res.status === 200) {
            this.notificationNumber = res.data // number 
         }
      },
   },
})